#-*- test-case-name: fjork.test.test_web -*-

#import urlparse

#import simplejson as json
from twisted.python import log
from twisted.internet import defer
from twisted.web import http, resource, server, static
from twisted.web import proxy

from fjork import settings
from fjork import utils

staticResource = static.File(
    settings.FJORK_ROOT.child('fjork').child('static').path
)

class Root(resource.Resource):
    @utils.logMethodTime
    def __init__(self, pool):
        resource.Resource.__init__(self)
        self.pool = pool
        self.putChild('static', staticResource)

    @utils.logMethodTime
    def getChild(self, path, request):
        log.msg("getChild:", path, request)
        if ".psp" in path:
            return proxy.ReverseProxyResource("localhost", 8080, "/" + path)
        if path == "":
            return self
        return resource.Resource.getChild(self, path, request)

    def _cbOk(self, content, request):
        log.msg("web._cbOk:", content, request)
        request.setResponseCode(http.OK)
        if settings.WEBKIT is True:
            index = content.find("<html>")
            request.write(content[index:])
        else:
            request.write(
                """<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
    <head>
        <title>Fjork</title>
    </head>
<body>
%s
</body>
</html>"""%(content)
            )
        request.finish()

    def _cbErr(self, failure, request):
        log.err("web._cbErr: %s"%(failure,))
        request.setResponseCode(http.INTERNAL_SERVER_ERROR)

    @utils.logMethodTime
    def render_GET(self, request):
        log.msg("render_GET:")
        d = defer.Deferred()
        # this deferred will be called back if the other side disconnects
        # d = request.notifyFinish()
        self.pool.queue(d, request, "/")
        d.addCallback(self._cbOk, request)
        d.addErrback(self._cbErr, request)
        return server.NOT_DONE_YET
